﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Ninject;
using System.ComponentModel;

namespace Lib.Web.Mvc.Ninject
{
    public class NinjectModelBinderProvider : IModelBinderProvider
    {
        #region Fields
        private IKernel _kernel;
        #endregion

        #region Constructor
        public NinjectModelBinderProvider(IKernel kernel)
        {
            _kernel = kernel;
        }
        #endregion

        #region IModelBinderProvider Members
        public IModelBinder GetBinder(Type modelType)
        {
            AttributeCollection allAttributes = TypeDescriptor.GetAttributes(modelType);
            if (allAttributes != null)
            {
                ModelBinderAttribute[] modelBinderAttributes = allAttributes.OfType<ModelBinderAttribute>().ToArray();
                if (modelBinderAttributes != null && modelBinderAttributes.Length == 1)
                    return _kernel.TryGet(modelBinderAttributes[0].BinderType) as IModelBinder;
            }

            return null;
        }
        #endregion
    }
}
